use std::ffi::CString;
use std::ptr;
use std::env;
use std::os::raw::c_char;
use std::fs;
use std::path::Path;
use std::ffi::OsString;

mod bindings {
    include!("./natserver.rs");
}

// 查找当前目录下的指定文件
fn find_file_in_current_dir(filename: &str) -> Option<String> {
    let current_dir = env::current_dir().unwrap();
    for entry in fs::read_dir(current_dir).unwrap() {
        let entry = entry.unwrap();
        let path = entry.path();
        if path.is_file() && path.file_name().unwrap() == filename {
            return Some(path.to_str().unwrap().to_string());
        }
    }
    None
}

pub async fn run(file_path: Option<&str>) {
    let mut argv = Vec::new();
    // 如果文件路径为空，尝试在当前目录下查找指定文件
    let file_path = match file_path {
        Some(path) => path.to_string(),
        None => {
            let default_file = "ripple.conf"; // 默认文件名
            find_file_in_current_dir(default_file).unwrap_or_else(|| {
                panic!("File '{}' not found in current directory", default_file);
            })
        }
    };

    // 将文件路径和 "-c" 添加到 argv 中
   
    argv.push("-c".to_string());
    argv.push(file_path);

    // 打印 argv
    println!("argv: {:?}", argv);

    // 将 Vec<String> 转换为 Vec<CString>
    let c_args: Vec<CString> = argv
        .into_iter()
        .map(|arg| CString::new(arg).unwrap())
        .collect();

    // 将 Vec<CString> 转换为 *mut *mut i8
    let mut c_argv: Vec<*mut c_char> = c_args.iter().map(|arg| arg.as_ptr() as *mut c_char).collect();
    c_argv.push(ptr::null_mut()); // 添加 NULL 终止符

    // 获取 argv 的长度（argc）
    let c_argc = 2; 
    unsafe {
        let handle = bindings::NewNats(c_argv.as_ptr() as *mut *mut i8, c_argc);
        let handle = handle as *mut std::os::raw::c_void;
        if handle == ptr::null_mut() {
            panic!("NewNats failed");
        }
        bindings::NatsStart(handle);
        bindings::NatsStop(handle);
    }
}